﻿using System;
using System.Windows.Forms;
using System.Reflection;
using System.Text;

namespace Pasys.PresentationCore
{
    public abstract class AbstractViewProvider : IPersistViewProvider, IDisposable
    {
        public IWin32Window Onwer { get; set; }

        public bool CreateViewEachTime { get; private set; }
        private Control SingleView;

        public void Dispose()
        {
            if (SingleView != null)
            {
                SingleView.Dispose();
                SingleView = null;
            }
        }

        public AbstractViewProvider() : this(false)
        {
        }

        /// <summary>
        /// 实例化AbstractViewProvider对象
        /// </summary>
        /// <param name="createViewEachTime">是否每次都创建一个新的View实例</param>
        public AbstractViewProvider(bool createViewEachTime)
        {
            CreateViewEachTime = createViewEachTime;
        }

        #region IViewProvider 成员

        private DockShell.ISmartPartInfo _viewInfo;

        public Control View
        {
            get
            {
                if (CreateViewEachTime)
                {
                    return CreateControl();
                }
                if (SingleView == null)
                {
                    SingleView = CreateControl();
                    if (SingleView != null)
                    {
                        SingleView.Disposed += _view_Disposed;
                    }
                }
                return SingleView;
            }
        }

        /// <summary>
        /// 指定如何显示View，如DockStyle等
        /// </summary>
        public virtual object ViewInfo
        {
            get
            {
                if (_viewInfo == null)
                {
                    _viewInfo = CreateViewInfo();
                }
                return _viewInfo;
            }
        }

        private void _view_Disposed(object sender, EventArgs e)
        {
            SingleView = null;
        }

        protected virtual  DockShell.ISmartPartInfo CreateViewInfo()
        {
            return null;
        }

        #endregion

        #region IPersistViewProviderViewProvider

        private static string getFullTypeName(string persistString)
        {

            System.IO.StringReader sr = new System.IO.StringReader(persistString);
            var fullTypeName = sr.ReadLine();
            sr.Close();
            return fullTypeName;

            //var fullTypeName = persistString;
            //string pattern = @"^[_a-zA-Z][_a-zA-Z0-9]*(\.[_a-zA-Z][_a-zA-Z0-9]*)*";
            //System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern);
            //if (regex.IsMatch(persistString))
            //{
            //    fullTypeName = regex.Match(persistString).Value;
            //}

            //return fullTypeName;
        }

        public  string GetPersistStringCallback()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(this.GetType().FullName);
            sb.Append(GetPersistParam());
            return sb.ToString();
        }

        public virtual string GetPersistParam()
        {
            return string.Empty;
        }


        public void SetPersistStringCallbackParam(string persistString)
        {
            System.IO.StringReader sr = new System.IO.StringReader(persistString);
            sr.ReadLine();
            var param = sr.ReadToEnd();
            sr.Close();
            if (!string.IsNullOrEmpty(param))
            {
                SetPersistParam(param);
            }

            //var fullTypeName = getFullTypeName(persistString);
            //int idx = persistString.IndexOf(fullTypeName);
            //SetPersistParam(persistString.Substring(idx + fullTypeName.Length));
        }

        public virtual void SetPersistParam(string param)
        { 
            
        }

        public static IPersistViewProvider FromPersistStringCallback(string persistString)
        {
            var fullTypeName = getFullTypeName(persistString);
            Type tp = null;
            tp = Type.GetType(string.Format("{0},{1}", fullTypeName, Assembly.GetExecutingAssembly()));

            Assembly[] als = AppDomain.CurrentDomain.GetAssemblies();
            foreach (var al in als)
            {
                tp = Type.GetType(string.Format("{0},{1}", fullTypeName, al));
                if (tp != null)
                {
                    break;
                }
            }

            if (tp == null)
            {
                return null;
            }

            var obj = Activator.CreateInstance(tp) as IPersistViewProvider;
            return obj;
        }


        #endregion

        protected abstract Control CreateControl();
    }
}